import { defineStore } from "pinia"
import { ref } from "vue"
import { loginAPI } from '@/apis/user.js'
import { useCartStore } from "./cart"
import { mergeCartAPI } from '@/apis/cart.js'


export const useUserStore = defineStore("user", () => {
  const cartStore = useCartStore()
  //1、定义state
  const userInfo = ref({})
  //2、定义action
  const getUserInfo = async ({ account, password }) => {
    const res = await loginAPI({ account, password })
    userInfo.value = res.result
    //更新购物车
    await mergeCartAPI(cartStore.cartList.map(item => {
      return {
        skuId: item.skuId,
        selected: item.selected,
        count: item.count
      }
    }))
  
    cartStore.updateNewList()
  }
  const logout = () => {
    userInfo.value = {}
    cartStore.clearCart()
  }
  //3、以对象的方式把state和action暴露出去
  return {
    userInfo,
    getUserInfo, logout
  }
}, {
  persist:true
  // 
  /* persist: [
    {
      paths: ['token'],
      key: 'xtx2024-user-token'
    },
    {
      paths: ['userInfo'],
      key: 'xtx2024-user-info'
    }] */
});